package main;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import side_server.Server;

public class ListPeers implements Runnable{
	private Socket socket;
	private String ip;
	private int port;
	private String files;
	
	public ListPeers(String ip, int port) throws UnknownHostException, IOException
	{
		super();
		this.ip=ip;
		this.port=port;
	}

	@Override
	public void run() {
		InputStream in;
		try {
			socket = new Socket(ip, port);
			in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
			
			socket.setSoTimeout(30000);
			files = br.readLine();
			if(files.equalsIgnoreCase("WAIT FOR MESSAGE"))
			{
				bw.write("LISTPEERS\n");
				bw.flush();
				files = br.readLine().replace(Server.SEP, "\n");
				System.out.println(files);
			}
			bw.write("OK\n");
			bw.flush();
		} catch (IOException e) {
			System.out.println("LISTFILES: ERRORE DURANTE L'ESECUZIONE DEL COMANDO");
		}
		
	}
}
